import smtplib
import ssl
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
from email.utils import formataddr

# 配置信息
qq_mail = '793757152@qq.com'
qq_password = 'wnqbdnxyzqphbfeh'
recipients = [
    {'name': '张三', 'email': 'yrqc53719@163.com'},
    {'name': '李四', 'email': '793757152@qq.com'}
]  # 带姓名和邮箱的收件人列表


# 邮件内容模板（支持个性化）
def create_message(recipient_name):
    message = MIMEMultipart()
    message['From'] = formataddr(('公司发件人', qq_mail))
    message['To'] = formataddr((recipient_name, recipient['email']))
    message['Subject'] = f'{recipient_name}，您的专属通知'

    # 个性化正文
    html_content = f"""
    <html>
    <body>
        <h2>尊敬的 {recipient_name}：</h2>
        <p>这是一封个性化群发邮件，附件是您的专属文件。</p>
    </body>
    </html>
    """
    message.attach(MIMEText(html_content, 'html', 'utf-8'))

    # 添加附件（可根据收件人不同附件）
    # with open(f'{recipient_name}_data.pdf', 'rb') as f:
    #     attach_part = MIMEApplication(f.read(), Name=f'{recipient_name}_data.pdf')
    #     attach_part['Content-Disposition'] = f'attachment; filename="{recipient_name}_data.pdf"'
    #     message.attach(attach_part)

    return message


# 逐个发送
try:
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL('smtp.qq.com', 465, context=context) as server:
        # server.set_debuglevel(1)  # 打印完整SMTP协议交互日志
        server.login(qq_mail, qq_password)

        for recipient in recipients:
            msg = create_message(recipient['name'])
            server.sendmail(qq_mail, [recipient['email']], msg.as_string())
            print(f"✅ 已发送给 {recipient['name']} ({recipient['email']})")

        print(f"🎉 共发送 {len(recipients)} 封邮件")
except Exception as e:
    print(f"❌ 发送失败: {e}")